package com.mvc.base.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.base.model.UserCompany;
import com.mvc.base.service.CompanyManager;
import com.mvc.base.service.UserCompanyManager;
import com.mvc.framework.web.MessageUtils;
import com.mvc.security.model.User;
import com.mvc.security.service.UserManager;

@Controller
@RequestMapping("userCompanyPrivilege")
public class UserCompanyPrivilegeController {
	@Autowired
	private UserCompanyManager	userCompanyPrivilegeManager;

	@Autowired
	private UserManager<User>	userManager;

	@Autowired
	private CompanyManager	   companyManager;

	@RequestMapping("save/{type}")
	public String save(HttpServletRequest request, @PathVariable Integer type) {
		String companyIds = request.getParameter("companyIds");
		String userIds = request.getParameter("userIds");
		List<UserCompany> userCompanyPrivileges = new ArrayList<UserCompany>();
		if (StringUtils.isNotBlank(companyIds)) {
			String[] company = companyIds.split(";");
			String[] users = userIds.split(";");
			for (int i = 0; i < company.length && i < users.length; i++) {
				if (StringUtils.isNotBlank(users[i])) {
					for (String userId : users[i].split(",")) {
						UserCompany userCompanyPrivilege = new UserCompany();
						userCompanyPrivilege.setCompanyId(Integer.parseInt(company[i]));
						userCompanyPrivilege.setUserId(Integer.parseInt(userId));
						userCompanyPrivileges.add(userCompanyPrivilege);
					}
				}
			}
		}
		userCompanyPrivilegeManager.saveUserCompanyPrivileges(userCompanyPrivileges, type);
		return "redirect:../config/" + type + MessageUtils.getMessage("操作成功");
	}
}
